/**
 * 分段专题图
 * 说明：可选择分段算法、分段数目、分段颜色
//  */
// segment_values
import sgisMapBase from '../../sgis.map.base'
import sgisLayerBase from '../../sgis.layer.base'
import sgisSpatialQuery from '../../sgis.spatial.query'
import dataAnalysis from '../../sgis.data.analysis'
import styleModify from './echarts.stylemodify' // 为图层设置透明度，可见性，zIndex而设置
import $ from 'jquery'
export default {
  layerNum: 0,
  // 默认配色方案  默认分为5段
  colors: [
    ['FEE5D9', 'FCAE91', 'FB6A4A', 'DE2D26', 'A50F15'],
    ['FEEDDE', 'FDBE85', 'FD8D3C', 'E6550D', 'A63603'],
    ['FFFFCC', 'C2E699', '78C679', '31A354', '006837'],
    ['FFFFCC', 'A1DAB4', '41B6C4', '2C7FB8', '253494'],
    ['F0F9E8', 'BAE4BC', '7BCCC4', '43A2CA', '0868AC'],
    ['EDF8FB', 'B2E2E2', '66C2A4', '2CA25F', '006D2C'],
    ['F6EFF7', 'BDC9E1', '67A9CF', '1C9099', '016C59'],
    ['F1EEF6', 'BDC9E1', '74A9CF', '2B8CBE', '045A8D'],
    ['EDF8FB', 'B3CDE3', '8C96C6', '8856A7', '810F7C']
  ],
  /**
   * {
        id:"",  // 图层id
        name:"",   // 图层名称
        datas:[    //数据支持多年数据展示
          {
            segment_values:[],  // 图层分段值
            values:[{"regioncode":"","rname":"","regiontype":"","value":"",},{}]
          }  // 数值信息
        ] 
   * }
   * @param {Object} map 地图对象
   * @param {Object} data  出图参数
   */
  createLayer (map, data) {
    let layerid = 'range_theme_' + data.id + '_' + new Date().getTime()
    let themeLayer = L.supermap.rangeThemeLayer(
      'ThemeLayer_' + new Date().getTime(), {
        id: layerid,
        // 开启hover高亮
        isHoverAble: true,
        opacity: 0.8,
        alwaysMapCRS: true,
        nodesClipPixel: 4 // 节点抽稀像素距离
      }
    )
    themeLayer.addTo(map)
    themeLayer.style = new SuperMap.ThemeStyle({
      shadowBlur: 16,
      shadowColor: '#000000',
      fillColor: '#FFFFFF'
    })
    themeLayer.highlightStyle = new SuperMap.ThemeStyle({
      stroke: true,
      strokeWidth: 4,
      strokeColor: 'blue',
      fillColor: '#00EEEE',
      fillOpacity: 0.8
    })
    // 用于专题图的值得字段名称
    themeLayer.themeField = 'value'
    // 分段风格数组
    themeLayer.styleGroups = this.getStyleGroups(data.datas[0].segment_values)
    this.addFeatures(data.datas[0].values, themeLayer)
    // 为themeLayer 注册修改color的方法
    themeLayer.setCustomColor = this.setCustomColor
    // 将数据绑定到图层，方便刷新图层
    themeLayer.setVisible = this.setVisible // 设置图层可见性
    themeLayer.setOpacity = this.setOpacity // 设置图层透明度
    themeLayer.getStyleGroups = this.getStyleGroups // 设置图层透明度
    themeLayer.layerId = layerid
    themeLayer.options = {
      ...themeLayer.options,
      ...this
    } // 自定义设置颜色时用到参数设置
    themeLayer.options.cusdata = data // 所有数据
    themeLayer.options.currdata = data.datas[0] // 当前数据
    // 绑定鼠标进入时间
    themeLayer.on('mousemove', this.showInfoWin)
    themeLayer.on('mouseout', this.closeInfoWin)
    themeLayer.setZIndexOffset = this.setZIndexOffset // 设置图层顺序函数
    themeLayer.container.style.zIndex = styleModify.curZindex // 为设置图层顺序调整特意设置
    styleModify.layerOrder[layerid] = styleModify.curZindex
    styleModify.curZindex -= 1
    // 保存一下图层信息
    let themeLayerInfo = {
      // 要保证此id和themeLayer的option中的id一致，此处只有根据元素id获得layer
      layerId: layerid,
      name: data.name,
      show: data.showThumbnails !== false,
      layer: themeLayer,
      type: 'themerange'
    }
    themeLayerInfo.html = this.calgraph(layerid, themeLayer.styleGroups)
    sgisLayerBase.setOverLayers(themeLayerInfo)
    return themeLayerInfo
  },
  /**
   * 根据分段值数组获取分段风格 默认分段为端
   * @param {Array} segment_values 分段值数组
   */
  getStyleGroups (segment_values) {
    let color = this.getColor ? this.getColor() : this.options.colors
    if (this.options && this.options.colors) {
      color = []
      for (const item of this.options.colors) {
        const value = item.slice(1)
        color.push(value)
      }
    }
    // if (this.colors.length > 0) {
    //   color = this.colors[0];
    //   this.colors.splice(0, 1);
    // }
    let styleGroups = []
    /**
     * 前后端分别用 -999999999999999999999999999   999999999999999999999999999
     * 保证覆盖到所有的值
     */
    for (let i = 0; i < segment_values.length; i++) {
      let style = {
        start: i === 0 ? -999999999999999999999999999 : segment_values[i - 1],
        end: i === segment_values.length - 1 ?
          999999999999999999999999999 : segment_values[i],
        style: {
          color: i === 0 ? 'transparent' : '#' + color[i - 1]
        }
      }
      styleGroups.push(style)
    }
    return styleGroups
  },
  // 循环去取颜色，防止两次出图时颜色一样
  getColor () {
    if (this.layerNum === 8) {
      this.layerNum = 0
    } else {
      this.layerNum++
    }
    if (!this.options) {
      return this.colors[this.layerNum]
    }
    if (this.options.layerNum === 8) {
      this.options.layerNum = 0
    } else {
      this.options.layerNum++
    }

    return this.options.colors[this.options.layerNum]
  },
  // 添加features
  addFeatures (values, layer) {
    let valueTemp = {}
    let regioninfos = []
    for (let i = 0; i < values.length; i++) {
      // 每一百个区划叠加一次，不一次性查询出来，村的边界数据太大
      let regioncode = values[i].regioncode
      let value = values[i].value
      let regiontype = values[i].regiontype
      valueTemp[regioncode] = value
      let regionInfo = {
        regioncode: regioncode,
        regiontype: regiontype
      }
      regioninfos.push(regionInfo)
      if (i > 0 && i % 100 === 0) {
        this.queryFeatures(valueTemp, regioninfos, layer)
        valueTemp = {}
        regioninfos = []
      }
    }
    if (valueTemp !== null && !$.isEmptyObject(valueTemp)) {
      this.queryFeatures(valueTemp, regioninfos, layer)
    }
  },
  queryFeatures (data, regioninfos, themeLayer) {
    let regiontype = regioninfos[0].regiontype
    sgisSpatialQuery.spatialQueryUtil.getFeaturesByRegionCodes(
      regioninfos,
      regiontype,
      function (serviceResult) {
        let result = serviceResult.result
        if (result && result.features) {
          let features = result.features
          // themeLayer.addFeatures();
          // 重新构造一下features
          for (let i = 0; i < features.features.length; i++) {
            let code = features.features[i].properties.QH_CODE
            features.features[i].properties['value'] = data[code]
          }
          themeLayer.addFeatures(features)
        }
      }
    )
  },
  /**
   * 自定义颜色修改
   * @param {Object} layer 图层
   * @param {Object} colorParam 自定义颜色参数
   * {
   *    color:[]
   * }
   */
  setCustomColor (layer, colorParam) {
    let currStyleGroups = layer.styleGroups
    /**
     * 判断颜色长度是否变化是否需要重新分段，
     * 1、如果分段数不变则直接调整颜色，重绘图层就可以
     * 2、如果分段数目发生改变则需要重新调整数据分段
     */
    const len = colorParam.colors.length
    this.options.colors = colorParam.colors
    if (currStyleGroups.length === len) {
      currStyleGroups = layer.styleGroups
      for (let i = 0; i < currStyleGroups.length; i++) {
        currStyleGroups[i].style.color = colorParam.colors[i]
      }
    } else {
      // 重新调整分段数目，获取新的styleGroups
      let dataTemp = layer.options.currdata.values
      let segment_values_temp = dataAnalysis.themerange.getSegmentByDataArr(
        dataTemp,
        len
      ); // 这个地方要根据data重新获取
      layer.options.currdata.segment_values = segment_values_temp
      currStyleGroups = layer.getStyleGroups(segment_values_temp)
    }
    this.options.refreshStyles(currStyleGroups, layer)
    this.options.calgraph(layer.layerId, layer.styleGroups, 'auto') // 更新图例
  },
  /**
   * 设置图层可见性
   */
  setVisible (visible) {
    this.container.style.visibility = visible
  },
  /* *设置图层透明度 */
  setOpacity (opacity) {
    this.container.style.opacity = opacity
  },
  /** 设置调整图层顺序函数*/
  setZIndexOffset (index) {
    styleModify.setZIndexOffset(index, this.layerId, this.container)
  },
  /* *图例样式计算 */
  calgraph (layerId, styleGroup, auto) {
    let tpl = ''
    const tplb = `<div style='background:#888;width:3px;height:3px;float:left'></div>`;
    const tplw = `<div style='background:white;width:3px;height:3px;float:left'></div>`;
    for (let i = 0; i < 24; i++) {
      if (i % 2) {
        tpl += tplw
      } else {
        tpl += tplb
      }
    }
    let html = `
     <div class="${layerId}" style='padding:10px;'>
        <ul style='padding:0;margin:0'>
    `;
    for (const key in styleGroup) {
      const item = styleGroup[key]
      html += `<li style='list-style:none;padding:5px 0'>`
      if (key === "0") {
        html += `<div style='display:inline-block;width:15px;height:15px;background:${item.style.color}'>${tpl}</div><span>&nbsp;&nbsp;&nbsp;无数据</span>`;
      } else if (key === styleGroup.length - 1 + "") {
        html += `<div style='display:inline-block;width:15px;height:15px;background:${item.style.color}'></div><span>&nbsp;&nbsp;&nbsp;&nbsp;&gt;&nbsp;${item.start}</span>`;
      } else {
        html += `<div style='display:inline-block;width:15px;height:15px;background:${item.style.color}'></div><span>&nbsp;&nbsp;&nbsp;&nbsp;${item.start}</span>
        &nbsp;-&nbsp;<span>${item.end}</span>`
      }
      html += `</li>`
    }
    html += `</ul>
     </div>`
    if (auto === 'auto') {
      const layers = sgisLayerBase.overLayers
      for (const key in layers) {
        if (layers[key].layerId === layerId) {
          layers[key].html = html
        }
      }
    }
    return html
  },
  /**
   * 刷新图层样式
   */
  refreshStyles (styleGroups, layer) {
    layer.styleGroups = styleGroups
    layer.redraw()
  },
  /**
   * 刷新图层数据
   * { 
      segment_values:[],  // 图层分段值
      values:[{"regioncode":"","rname":"","regiontype":"","value":"",},{}]  // 数值信息
     }
   */
  refreshDatas (data, layer) {
    // 获取分段范围，生成分段样式
    let currStyleGroups = this.getStyleGroups(data.segment_values)
    for (let i = 0; i < currStyleGroups.length; i++) {
      currStyleGroups[i].start =
        i === 0 ? -999999999999999999999999999 : segment_values[i - 1]
      currStyleGroups[i].end =
        i === segment_values.length - 1 ?
        999999999999999999999999999 :
        segment_values[i]
    }
    // 清除features,进行重绘
    layer.clear ()
    // 重设图层样式
    layer.styleGroups = styleGroups
    // 添加features
    layer.options.currdata = data
    this.addFeatures(data.values, layer)
  },
  // 打开信息弹窗
  _this: this,
  showInfoWin (e) {
    if (e.target && e.target.refDataID) {
      // if (e.target.infowin) {
      //   e.target.infowin.remove();
      //   e.target.infowin = null;
      // }
      // 此处获取图层原属的html,并从中获取到和layer一致的id
      let layerId = e.event.path[2].id
      let themeLayerInfo = sgisLayerBase.getOverLayerById(layerId) // 此处根据id获取layer
      let feature = themeLayerInfo.layer.getFeatureById(e.target.refDataID)
      if (!feature) {
        return
      }
      // 此处根据feature构造显示的内容
      let contentHTML = '<div>hello world!</div>'
      let infowin = null
      if (!e.target.infowin || e.target.infowin === null) {
        infowin = L.popup()
        infowin.setLatLng(sgisMapBase.getMousePoint())
        infowin.setContent(contentHTML)
        infowin.openOn(sgisMapBase.getMap())
        e.target.infowin = infowin
      } else {
        infowin = e.target.infowin
      }
      infowin.setLatLng(sgisMapBase.getMousePoint())
      infowin.update()
    }
  },
  // 关闭弹窗
  closeInfoWin (e) {
    if (e) {
      if (e.target && e.target.infowin) {
        e.target.infowin.remove()
        e.target.infowin = null
      }
    }
  }
}
